<?php
namespace Home\Controller;
use Home\Controller\BaseController;

require_once 'Qiniu/autoload.php';
use \Qiniu\Auth;
use \Qiniu\Storage\UploadManager;
C('TOKEN_ON', false);

class SpecialController extends BaseController {
    /**
     * 专题列表
     */
    public function index() {
        $spec_name = I('get.spec_name');
        $map['org_id'] = $this->adminInfo['organ'];

        $this->channelId = $this->channelId ? $this->channelId : array(-1);
        $map['channel_id'] = array('in', $this->channelId);
        if($spec_name) {
            $map['spec_name'] = array("like","%{$spec_name}%");
        }

        $model = M('Spec');
        $total = $model->where($map)->count();
        $page = new \Think\Page($total,10);
        $show = $page->show();

        $list = $model->where($map)->limit($page->firstRow .',' . $page->listRows)->select();

        $putPolicy=array(
            'saveKey'=>'spec/$(etag)',
        );
        $upAuth = new Auth(C('QINIU_AK'), C('QINIU_SK'));
        $bucket = C('QINIU_BUCKET');
        $uploadToken = $upAuth->uploadToken($bucket,null, 3600,$putPolicy);

        $channel_list=M('Channel')->where(array('chid'=>array('in', $this->channelId),'status'=>1))->select();
        $this->assign('channel_list', $channel_list);

        $this->assign('uploadToken', $uploadToken);
        $this->assign('active', '专题管理');
        $this->assign('list', $list);
        $this->assign('showpage', $show);
        $this->display();
    }

    /**
     * 添加专题
     */
    public function addSpec() {
        if(IS_POST) {
//            $params['__hash__'] = I('post.__hash__');
            $params['spec_name'] = I('post.spec_name');
            $params['sort'] = I('post.sort');
            $params['image_url'] = I('post.image_url');
            $params['org_id'] = $this->adminInfo['organ'];
            $params['channel_id'] = I('post.channel_id');

            $model = D('Spec');
            if($model->create($params)) {
                $rs = $model->add();
                if($rs) {
                    $this->success('专题添加成功', U("index"));
                } else {
                    $this->error('专题添加失败');
                }
            } else {
                $this->error($model->getError());
            }

        } else {
            $this->display();
        }
    }

    /**
     * 修改专题
     */
    public function editSpec() {
        $model = D('Spec');
        if(IS_POST) {
//            $params['__hash__'] = I('post.__hash__');
            $params['id'] = I('post.id');
            $params['spec_name'] = I('post.spec_name');
            $params['sort'] = I('post.sort');
            $image_url = I('post.image_url');
            $params['channel_id'] = I('post.channel_id');
            $image_url && $params['image_url'] = $image_url;

            if($model->create($params)) {
                $rs = $model->save();
                if($rs) {
                    $this->success('专题修改成功', U("index"));
                } else {
                    $this->error('专题修改失败');
                }
            } else {
                $this->error($model->getError());
            }

        } else {
            $this->display();
        }

//        $id = I('get.id');
//        $info = $model->find($id);
//
//        $this->assign('info', $info);
//        $this->display();
    }

    public function details() {
        $id = I('get.id');

        $list = array();
        if($id) {
            $map['spec_id'] = $id;
            $title = I('get.title');
            $s_time = I('get.s_time', 0);
            $e_time = I('get.e_time', 0);

            if($title) {
                $map['title'] = array('like', "%{$title}%");
            }

            if($s_time || $e_time) {
                $e_time = $e_time ? strtotime($e_time . '23:59:59') : (time() + (20 * 365 * 24 * 60 * 60));
                $map['start_time'] = array(array('egt', strtotime($s_time)), array('elt', $e_time));
            }

            $spec_record_model = M('SpecRecord');
            $spec_list = $spec_record_model->alias('sr')->field('sr.id spec_re_id, l.title, l.image_url, l.start_time')->join('__LIVE__ l on l.group_id = sr.live_group_id')->where($map)->group('group_id')->select();
//            echo $spec_record_model->getLastsql();
            $page = new \Think\Page(count($spec_list),8);
            $show = $page->show();

            $spec_list = $spec_record_model->alias('sr')
                         ->field('sr.id spec_re_id,sr.spec_id, l.title, l.image_url, l.start_time,l.group_id')
                         ->join('__LIVE__ l on l.group_id = sr.live_group_id')
                         ->where($map)->limit($page->firstRow .',' . $page->listRows)->group('group_id')->order('sr.sort desc, l.start_time desc')->select();
        }

        $this->assign('showpage', $show);
        $this->assign('list', $spec_list);
        $this->display();
    }

    /**
     * 撤回
     */
    public function reCall() {
        if(IS_GET) {
            $id = I('get.id');
        } elseif(IS_POST) {
            $id = I('post.id');
            is_array($id) && $id = implode(',', $id);
        }

        if(empty($id)) {
            $message['status'] = -1;
            $message['msg'] = '选项不能为空';
            $this->ajaxReturn($message);
        }

        $map['id'] = array('in', $id);
        $res = M('SpecRecord')->where($map)->delete();

        if($res !== false) {
            $this->success('撤回成功', U("details", array('id' => I('param.spec_id'))));
        } else {
            $this->error('撤回失败');
        }
    }

    /**
     * 上次封面图片
     */
    public function uploadImage() {
        $info = $_FILES['file'];

        if($info['error']!=0) {
            $mess['jsonrpc'] = "2.0";
            $mess['error']['code'] = "102";
            $mess['error']['message'] = $info['error'];
            $mess['error']['id'] = "id";
        }else{
            $auth = new Auth(C('QINIU_AK'), C('QINIU_SK'));

            $policy = array(
                'saveKey' => "spec/$(etag)"
            );
            $token = $auth->uploadToken(C('QINIU_BUCKET'),null, 3600, $policy);

            $filePath =$info['tmp_name'];
            $uploadMgr = new UploadManager();
            list($ret, $err) = $uploadMgr->putFile($token, null, $filePath);

            if ($err !== null) {
                $mess['jsonrpc'] = "2.0";
                $mess['error']['code'] = "102";
                $mess['error']['message'] = $err;
                $mess['error']['id'] = "id";
            } else {
                $mess['jsonrpc'] = "2.0";
                $mess['result'] = C('QINIU_HOST') . '/' . $ret['key'];
                $mess['id'] = "id";
            }
        }
        exit(json_encode($mess));
    }

    public function ajaxGetSpec() {
        $id = I('get.id');
        if($id) {
            $info = M('Spec')->where(array('id' => $id))->find();
            if($info) {
                $mess['code'] = 0;
                $mess['message'] = '';
                $mess['info'] = $info;
            } else {
                $mess['code'] = 1;
                $mess['message'] = '不存在此专题';
            }

        } else {
            $mess['code'] = 1;
            $mess['message'] = '未知ID';
        }

        exit(json_encode($mess));
    }

    /**
     * 签发列表
     */
    public function getIssueLive() {
        $spec_id = I('get.spec_id'); // 专题ID
//        $total = M('Live')->alias('l')
//                ->join('__SPEC_RECORD__ sr ON l.group_id = sr.live_group_id', 'left')
//                ->where(array('spec_id' => $spec_id))->group('group_id')->select();
//        $total=count($total);
//        $page = new \Think\Page($total, 8);
//        $show = $page->show();
//
//        $list = M('Live')->alias('l')
//            ->join('__SPEC_RECORD__ sr ON l.group_id = sr.live_group_id ', 'left')
//            ->where(array('spec_id' => $spec_id))->limit($page->firstRow .',' . $page->listRows)
//            ->group('group_id')->select();

        $map = array();
        $title = I('get.title');
        $s_time = I('get.s_time', 0);
        $e_time = I('get.e_time', 0);

        if($title) {
            $map['title'] = array('like', "%{$title}%");
        }

        if($s_time || $e_time) {
            $e_time = $e_time ? strtotime($e_time . '23:59:59') : (time() + (20 * 365 * 24 * 60 * 60));
            $map['start_time'] = array(array('egt', strtotime($s_time)), array('elt', $e_time));
        }

        $model = M('Live');

        $first_result = M('SpecRecord')->field('live_group_id')->where(array('spec_id' => $spec_id))->group('live_group_id')->select();
        $groups = array();
        foreach($first_result as $val) {
            $groups[] = $val['live_group_id'];
        }

        if($groups) {
            $map['group_id'] = array('not in', $groups);
        }

        $map['column_id'] = array('in', $this->channelId);
        $list = $model->where($map)->group('group_id')->select();
        $total = count($list);
        $page = new \Think\Page($total, 6);
        $show = $page->show();

        $liveList = $model->where($map)
            ->order('sort Desc, create_time desc')
            ->group('group_id')
            ->limit($page->firstRow .',' . $page->listRows)
            ->select();

        foreach($liveList as $key => $val) {
//            $tmp = M('SpecRecord')->where(array('spec_id' => $spec_id, 'live_group_id' => $val['group_id']))->find();
            $liveList[$key]['realname'] = M('UserInfo')->where(array('uid' => $val['apply_id']))->getField('realname');
//            if($tmp) {
//                $liveList[$key]['is_add'] = 1;
//            } else {
//                $liveList[$key]['is_add'] = 0;
//            }
        }


        $this->assign('showpage', $show);
        $this->assign('liveList', $liveList);
        $this->display('issueLive');
    }

    /**
     * 签发直播到专题
     */
    public function addIssueLive() {
        $group_ids = I('post.gids');
        $spec_id = I('post.specid');

        if($group_ids && $spec_id) {
            $group_ids = explode(',', $group_ids);
            $params['spec_id'] = $spec_id;

            foreach($group_ids as $key => $val) {
                $is_on = M('SpecRecord')->where(array('spec_id' => $spec_id, 'live_group_id' => $val))->count();
                if(!$is_on) {
                    $params['live_group_id'] = $val;
                    $params['type'] = 'live';
                    $res = M('SpecRecord')->add($params);
                    if(!$res) {
                        $mess['status'] = -1;
                        $mess['msg'] = '部分直播签发失败';
                        exit(json_encode($mess));
                    }
                }
            }

            $mess['status'] = 1;
            $mess['msg'] = '签发成功';
        } else {
            $mess['status'] = -1;
            $mess['msg'] = '参数错误';
        }

        exit(json_encode($mess));
    }

    public function delSpecial() {
        $id = I('post.id');
//        $this->success('专题不存在');exit;
        if($id) {
            try {
                M()->startTrans();

                $row = M('Spec')->where(array('id' => $id))->delete();
                if($row) {
                    $total = M('SpecRecord')->where(array('spec_id' => $id))->count();
                    $res = M('SpecRecord')->where(array('spec_id' => $id))->delete();

                    if($res != $total) {
                        throw new \Exception('专题相关内容删除失败');
                    }

                } else {
                    throw new \Exception('专题删除失败');
                }

                M()->commit();

                $this->success('删除成功');
                exit;
            } catch (\Exception $e) {
                M()->rollback();
                $this->error($e->getMessage());
            }

        } else {
            $this->error('专题不存在');
        }
    }
}